package com.twang.stock.service.jinyan;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.jayway.jsonpath.JsonPath;
import com.twang.stock.entity.CompanyCodeInfo;
import com.twang.stock.entity.HotTag;
import com.twang.stock.mapper.CompanyCodeInfoMapper;
import com.twang.stock.task.old.GaiNianZiJingPaiHangTask;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.assertj.core.util.Lists;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 更新池
 */
@Slf4j
@Service
public class UpdateStockCoreService {
    private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36";
    public static Pattern regex = Pattern.compile("<span class=\"page_info\">(.*)</span>");

    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;

    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;


    private final AtomicInteger numSize = new AtomicInteger();

    public void batchExcute(int page) {
        for (numSize.set(page); numSize.get() < 267; ) {
            //numSize = i;
            numSize.incrementAndGet();
            int finalsize = numSize.get();
            asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                log.info("----------------------->>>>>>>>>> page={}", finalsize);
                List<CompanyCodeInfo> list=updateCore(finalsize);
                getByXUeQiu(list);
            });
        }
        numSize.set(0);
    }

    public void aaaaa(String[] args) {
        List<CompanyCodeInfo> record = Lists.newArrayList();
        CompanyCodeInfo companyCodeInfo = new CompanyCodeInfo();
        companyCodeInfo.setCompanyCode("sz000888");
        record.add(companyCodeInfo);
        companyCodeInfo = new CompanyCodeInfo();
        companyCodeInfo.setCompanyCode("sz000737");
        record.add(companyCodeInfo);
        companyCodeInfo = new CompanyCodeInfo();
        companyCodeInfo.setCompanyCode("sz000988");
        record.add(companyCodeInfo);
        getByXUeQiu(record);
    }

    public void getByXUeQiu(List<CompanyCodeInfo> record) {
        StringBuffer stringBuffer = new StringBuffer();
        int j = 0;
        Map<String, CompanyCodeInfo> recordMaps = new HashedMap();
        for (int i = 0; i < record.size(); i++) {
            if (j == 99) {
                setStockMarketCapital(stringBuffer, recordMaps);
                j = 0;
                stringBuffer = new StringBuffer();
                ;
            } else {
                if (j == 0) {
                    stringBuffer.append(record.get(i).getCompanyCode().toUpperCase());
                } else {
                    stringBuffer.append(",").append(record.get(i).getCompanyCode().toUpperCase());
                }
                recordMaps.put(record.get(i).getCompanyCode(), record.get(i));
                j++;
            }
        }
        //收尾
        if (StringUtils.isNotEmpty(stringBuffer)) {
            setStockMarketCapital(stringBuffer, recordMaps);
        }
    }


    public  void getDataByDfcf() {
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        StringBuffer url = new StringBuffer("").append("http://83.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112405211955410183502_1677071364988&pn=1&pz=5000&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&wbp2u=%7C0%7C0%7C0%7Cweb&fid=f6&fs=m%3A0%2Bt%3A6%2Cm%3A0%2Bt%3A80%2Cm%3A1%2Bt%3A2%2Cm%3A1%2Bt%3A23%2Cm%3A0%2Bt%3A81%2Bs%3A2048&fields=f12%2Cf13%2Cf14%2Cf15%2Cf16%2Cf17%2Cf18%2Cf20%2Cf21&_=1677071364995");
        try {
            String htmlForStock = GaiNianZiJingPaiHangTask.getHtmlStrByUrlDfcf(url.toString(), httpClient, "", USER_AGENT);
            log.info("该网页存在,正在解析:{}", htmlForStock);
            htmlForStock =htmlForStock.split("\\(")[1].split("\\)")[0].toString();
            String dataList = JsonPath.read(htmlForStock, "$.data.diff").toString();
            List<Object> objectsList = JSONObject.parseArray(dataList, Object.class);
            objectsList.forEach(item -> {
                String companyCode = JsonPath.read(JSONObject.toJSONString(item), "$.f12").toString();

                String marketCapital = JsonPath.read(JSONObject.toJSONString(item), "$.f20").toString();

                Example example=new Example(CompanyCodeInfo.class);
                example.createCriteria().andLike("companyCode","%"+companyCode+"%");
                List<CompanyCodeInfo> list=companyCodeInfoMapper.selectByExample(example);
                if(CollectionUtils.isNotEmpty(list)) {
                    CompanyCodeInfo recordInfo = list.get(0);
                    recordInfo.setMarketValue(new BigDecimal(marketCapital).divide(new BigDecimal(100000000)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    recordInfo.setUpdateTime(HolidayCopy.getRealToday());
                    recordInfo.setModifyTime(new Date());
                    companyCodeInfoMapper.updateByPrimaryKey(recordInfo);
                }

            });
        } catch (Exception e) {

        }
    }








    /**
     * 更新市值
     *
     * @param stringBuffer
     * @param recordMaps
     */
    private void setStockMarketCapital(StringBuffer stringBuffer, Map<String, CompanyCodeInfo> recordMaps) {
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        StringBuffer url = new StringBuffer("").append("http://stock.xueqiu.com/v5/stock/realtime/quotec.json?symbol=");
        try {
            url.append(stringBuffer.toString());

            String htmlForStock = GaiNianZiJingPaiHangTask.getHtmlStrByUrl(url.toString(), httpClient, "", USER_AGENT);
            log.info("该网页存在,正在解析:{}", htmlForStock);
            String dataList = JsonPath.read(htmlForStock, "$.data").toString();
            List<Object> objectsList = JSONObject.parseArray(dataList, Object.class);
            objectsList.forEach(item -> {
                String companyCode = JsonPath.read(JSONObject.toJSONString(item), "$.symbol").toString();

                String marketCapital = JsonPath.read(JSONObject.toJSONString(item), "$.market_capital").toString();
                String amount = JsonPath.read(JSONObject.toJSONString(item), "$.amount").toString();

                CompanyCodeInfo recordInfo = recordMaps.get(companyCode.toLowerCase());
                recordInfo.setMarketValue(new BigDecimal(marketCapital).divide(new BigDecimal(100000000)).setScale(2, BigDecimal.ROUND_HALF_UP));
                recordInfo.setTradingVolume(new BigDecimal(amount));
                companyCodeInfoMapper.updateByPrimaryKey(recordInfo);
            });
        } catch (Exception e) {

        }
    }

    public List<CompanyCodeInfo> updateCore(int page) {
        List<CompanyCodeInfo> recordList = Lists.newArrayList();
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();

        /**
         * 成交额：http://q.10jqka.com.cn/index/index/board/all/field/cje/order/desc/page/1/ajax/1/
         * 涨跌幅：http://q.10jqka.com.cn/index/index/board/all/field/zdf/order/desc/page/1/ajax/1/
         */

        StringBuffer url = new StringBuffer("").append("https://q.10jqka.com.cn/index/index/board/all/field/zdf/order/desc/page/").append(page).append("/ajax/1/");
        try {
            // 停留一秒后开始任务
            // Thread.sleep(1000);
            // 发送请求，并执行
            String htmlForStock = GaiNianZiJingPaiHangTask.getHtmlStrByUrl(url.toString(), httpClient, "", USER_AGENT);
            // 网页内容解析
            log.info("该网页存在,正在解析:{}", htmlForStock);
            Document doc = Jsoup.parse(htmlForStock);
            // 获取table表的行集合元素
            Elements trs = doc.select("table[class=m-table m-pager-table]").select("tr");
            String elements = doc.getElementById("m-page").html();
            String result = "";
            int pageSize = 0;
            try {

                Matcher regexMatcher = regex.matcher(elements);
                if (regexMatcher.find()) {
                    result = regexMatcher.group().split(">")[1].split("<")[0].split("/")[1];
                }
                pageSize = Integer.valueOf(result);
            } catch (Exception ex) {
                log.info("error ={}", ex);
            }
            //序号 代码 名称 现价 涨跌幅(%)    涨跌  涨速(%)   换手(%)   量比  振幅(%)   成交额 流通股 流通市值    市盈率 加自选
            //板块编码
            for (int j = 1; j < trs.size(); j++) {
                Elements tds = trs.get(j).select("td");
                //code
                String code = tds.get(1).html().split("/")[3];
                CompanyCodeInfo param = new CompanyCodeInfo();
                if (code.startsWith("6")) {
                    code = "sh" + code;
                } else {
                    code = "sz" + code;
                }
                param.setCompanyCode(code);
                CompanyCodeInfo record = companyCodeInfoMapper.selectOne(param);
                Boolean newFlag = Boolean.FALSE;
                if (null == record) {
                    record = new CompanyCodeInfo();
                    record.setCompanyCode(code);
                    newFlag = Boolean.TRUE;
                }
                //name
                String codeName = tds.get(2).html().split("/")[4].split(">")[1].replace("<", "");
                record.setShortName(codeName);
                //流通市值
                record.setMarketCapitalization(returnNum(tds.get(12).html()));
                //成交额
                record.setTradingVolume(returnNum(tds.get(10).html()));
                //PE
                record.setPe(tds.get(13).html());
                record.setUpdateTime(HolidayCopy.getRealToday());
                record.setModifyTime(new Date());
                if (code.startsWith("sz8") || code.startsWith("sz2") || code.startsWith("sz4") || record.getShortName().contains("退") || record.getShortName().contains("B") || record.getShortName().contains("*ST") || record.getShortName().contains("*")) {
                    continue;
                } else {
                    //更新
                    if (newFlag) {
                        companyCodeInfoMapper.insert(record);
                    } else {
                        companyCodeInfoMapper.updateByPrimaryKey(record);
                    }
                    recordList.add(record);
                }
            }
            if (page < pageSize) {
                page++;
                //updateCore(page);
            }
        } catch (Exception e) {
            log.error("erro={}", e);
        }
        return recordList;
    }

    private BigDecimal returnNum(String str) {
        try {
            if (str.contains("亿")) {
                //成交额
                return new BigDecimal(str.replace("亿", ""));
            } else if (str.contains("万")) {
                str = str.replace("万", "");
                return new BigDecimal(str).divide(BigDecimal.valueOf(10000), 6, BigDecimal.ROUND_HALF_UP);
            }
        } catch (Exception e) {
            log.error("error----------------->str=", str);
        }
        return BigDecimal.ZERO;
    }

}
